import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { AppError, Notification } from '@/types'

export const useAppStore = defineStore('app', () => {
  // State
  const loading = ref(false)
  const error = ref<AppError | null>(null)
  const notifications = ref<Notification[]>([])
  const sidebarCollapsed = ref(false)
  const sidebarMobileOpen = ref(false)
  const pageTitle = ref('X-Synergy OS')
  const breadcrumbs = ref<{ name: string; path?: string }[]>([])

  // App metadata
  const appInfo = ref({
    name: 'X-Synergy OS',
    version: '1.0.0',
    description: 'AI驱动的智能ERP系统',
    logo: '/logo.svg'
  })

  // Getters
  const hasError = computed(() => !!error.value)
  const hasNotifications = computed(() => notifications.value.length > 0)
  const unreadNotifications = computed(() => 
    notifications.value.filter(n => !n.read).length
  )

  // Actions
  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  const setError = (appError: AppError | null) => {
    error.value = appError
  }

  const clearError = () => {
    error.value = null
  }

  const createError = (code: string, message: string, details?: string): AppError => {
    return {
      code,
      message,
      details,
      timestamp: new Date()
    }
  }

  const handleError = (err: any, context?: string) => {
    console.error('App Error:', err, context)
    
    const appError = createError(
      err.code || 'UNKNOWN_ERROR',
      err.message || '发生未知错误',
      context
    )
    
    setError(appError)
    
    // Also show as notification
    addNotification({
      type: 'error',
      title: '错误',
      message: appError.message,
      duration: 5000
    })
  }

  // Notification management
  const addNotification = (notification: Omit<Notification, 'id'>) => {
    const id = `notification_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    const newNotification: Notification = {
      id,
      read: false,
      timestamp: new Date(),
      duration: 4000,
      ...notification
    }

    notifications.value.unshift(newNotification)

    // Auto remove if not persistent
    if (!newNotification.persistent && newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }

    return id
  }

  const removeNotification = (id: string) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index !== -1) {
      notifications.value.splice(index, 1)
    }
  }

  const markNotificationRead = (id: string) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }

  const markAllNotificationsRead = () => {
    notifications.value.forEach(n => {
      n.read = true
    })
  }

  const clearNotifications = () => {
    notifications.value = []
  }

  const clearReadNotifications = () => {
    notifications.value = notifications.value.filter(n => !n.read)
  }

  // Success/Error/Warning/Info helpers
  const showSuccess = (message: string, title = '成功') => {
    return addNotification({
      type: 'success',
      title,
      message,
      duration: 3000
    })
  }

  const showError = (message: string, title = '错误') => {
    return addNotification({
      type: 'error',
      title,
      message,
      duration: 5000
    })
  }

  const showWarning = (message: string, title = '警告') => {
    return addNotification({
      type: 'warning',
      title,
      message,
      duration: 4000
    })
  }

  const showInfo = (message: string, title = '信息') => {
    return addNotification({
      type: 'info',
      title,
      message,
      duration: 3000
    })
  }

  // Sidebar management
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    localStorage.setItem('sidebar_collapsed', sidebarCollapsed.value.toString())
  }

  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed
    localStorage.setItem('sidebar_collapsed', collapsed.toString())
  }

  const toggleMobileSidebar = () => {
    sidebarMobileOpen.value = !sidebarMobileOpen.value
  }

  const setMobileSidebarOpen = (open: boolean) => {
    sidebarMobileOpen.value = open
  }

  // Page management
  const setPageTitle = (title: string) => {
    pageTitle.value = title
    document.title = `${title} - ${appInfo.value.name}`
  }

  const setBreadcrumbs = (crumbs: { name: string; path?: string }[]) => {
    breadcrumbs.value = crumbs
  }

  const addBreadcrumb = (name: string, path?: string) => {
    breadcrumbs.value.push({ name, path })
  }

  const clearBreadcrumbs = () => {
    breadcrumbs.value = []
  }

  // Connection status
  const isOnline = ref(navigator.onLine)
  const connectionStatus = computed(() => isOnline.value ? 'online' : 'offline')

  const updateOnlineStatus = () => {
    isOnline.value = navigator.onLine
    
    if (isOnline.value) {
      showSuccess('网络连接已恢复')
    } else {
      showWarning('网络连接已断开')
    }
  }

  // Performance monitoring
  const performanceMetrics = ref({
    loadTime: 0,
    renderTime: 0,
    memoryUsage: 0
  })

  const updatePerformanceMetrics = () => {
    if (performance && performance.memory) {
      performanceMetrics.value.memoryUsage = Math.round(
        (performance.memory as any).usedJSHeapSize / 1024 / 1024
      )
    }
  }

  // Initialize store
  const initialize = () => {
    // Load sidebar state
    const sidebarState = localStorage.getItem('sidebar_collapsed')
    if (sidebarState !== null) {
      sidebarCollapsed.value = sidebarState === 'true'
    }

    // Listen for online/offline events
    window.addEventListener('online', updateOnlineStatus)
    window.addEventListener('offline', updateOnlineStatus)

    // Monitor performance
    setInterval(updatePerformanceMetrics, 5000)

    // Set initial page title
    setPageTitle('AI助手')
  }

  // Cleanup
  const cleanup = () => {
    window.removeEventListener('online', updateOnlineStatus)
    window.removeEventListener('offline', updateOnlineStatus)
  }

  return {
    // State
    loading,
    error,
    notifications,
    sidebarCollapsed,
    sidebarMobileOpen,
    pageTitle,
    breadcrumbs,
    appInfo,
    isOnline,
    performanceMetrics,
    
    // Getters
    hasError,
    hasNotifications,
    unreadNotifications,
    connectionStatus,
    
    // Error management
    setLoading,
    setError,
    clearError,
    createError,
    handleError,
    
    // Notification management
    addNotification,
    removeNotification,
    markNotificationRead,
    markAllNotificationsRead,
    clearNotifications,
    clearReadNotifications,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    
    // Sidebar management
    toggleSidebar,
    setSidebarCollapsed,
    toggleMobileSidebar,
    setMobileSidebarOpen,
    
    // Page management
    setPageTitle,
    setBreadcrumbs,
    addBreadcrumb,
    clearBreadcrumbs,
    
    // Lifecycle
    initialize,
    cleanup
  }
})
